<template>
    <div class="big">
        <div class="listbox" ref="listbox">
            <div class="list" v-if="shopLists.length!=0">
                <div data-type="0" class="listchild" v-for="(item,index) in shopLists" :key="index" @click.stop="toNext('categoryDetail',{cateNo: item.productNo})">
                    <div class="imgshou" @touchend.capture="touchEnd" @touchstart.capture="touchStart">
                        <p ref="checkbox" class="cartP"> <input type="checkbox" :id="index" class="regular-checkbox" v-model="item.selectbox" @click="change(item,true)" />
                            <label :for="index"></label>
                        </p>
                        <img :src="item.picUrl" alt="">
                        <div class="conts">
                            <p>{{item.productName | sliceString(8)}}</p>
                            <p>
                                <span>{{item.salePrice}}元</span>
                                <span ref="number" class="conts-con">
                                    <x-number v-model="item.buyNumber" :min="1" @on-change="change(item)" class="xnumber" width="30px" ref="xnumber" :fillable=true :max="50"></x-number>
                                </span>
                            </p>
                            <p class="guige">
                                <span v-for="(itemchild,indexchild) in item.specList" :key="indexchild">{{itemchild.specName | sliceString(15)}}</span>
                            </p>
                        </div>
                    </div>
                    <div class="delte" @click="deleteItem($event,index,item)">删除</div>
                </div>
            </div>
            <div class="nodata" v-if="showBg">
                <img src="./../../assets/noshop.png" alt="">
                <p class="fontcolor">暂无商品,去看看别的吧</p>
            </div>
        </div>
        <diV class="shopfoot">
            <div class="confoot">
                <div class="left">
                    <div class="one">
                        <p class="check"><input type="checkbox" id="indexcheck" class="regular-checkbox" v-model="checkall" @click="selectdAll"/>
                            <label for="indexcheck"></label>
                        </p>
                        <p>{{!this.checkall?'全选':'取消全选'}}</p>
                    </div>
                    <div class="two">合计：￥{{shopprice}}</div>
                </div>
                <div class="button" @click="settlement()">结算</div>
            </div>
        </diV>
        <div class="cont"></div>
    </div>
</template>
<script>
// 1实物 2彩票 3券
// payMethod
// 1-RMB
// 2-积分
// 3-RMB+积分
import { XNumber } from "vux";
import { MessageBox, Toast } from "mint-ui";
import { shoppingOrders, getShopping, deletShop, Shopset } from "request";
import mixins from "mixins";
export default {
    mixins: [mixins],
    data() {
        return {
            checkall: false,
            bottomlist: [],
            route: {},
            shopNum: 0,
            shopprice: 0,
            shopIntergral: 0,
            shopType: "",
            freights: 0,
            startX: 0,
            endX: 0,
            checkallfalse: "",
            shopLists: []
        };
    },
    components: {
        XNumber
    },
    computed: {
        imgUrl() {
            return this.$store._modules.root._children.a.state;
        }
    },
    created() {
        // $router 直接监听无效，尚未查明，故作深拷贝处理
        this.route = Object.assign({}, this.$route);
        this.getShopdata();
        // this.clicks()
    },
    updated() {
        if (this.$refs.checkbox == undefined) {
        } else {
            for (var i = 0; i < this.$refs.checkbox.length; i++) {
                this.$refs.checkbox[i].addEventListener(
                    "click",
                    this.clicks,
                    false
                );
                this.$refs.number[i].addEventListener(
                    "click",
                    this.clicks,
                    false
                );
            }
        }
    },
    beforeDestroy() {
        document.removeEventListener("click", this.clicks, false);
    },
    methods: {
        //点击监听用户操作
        clicks(ev) {
            ev.stopPropagation();
            this.sTimeout();
        },
        // allclicks() {
        //     this.sTimeout();
        // },
        sTimeout() {
            setTimeout(() => {
                if (this.shopLists.length != 0) {
                    let allstr = [];
                    let allfalsenum = 0;
                    let alltruenum = 0;
                    this.shopprice = 0;
                    this.shopIntergral = 0;
                    for (var i = 0; i < this.shopLists.length; i++) {
                        if (this.shopLists[i].selectbox) {
                            this.shopprice += Number(
                                this.shopLists[i].buyNumber *
                                    this.shopLists[i].salePrice *
                                    100
                            );
                            this.shopIntergral +=
                                this.shopLists[i].integral *
                                this.shopLists[i].buyNumber;
                        }
                        allstr.push(String(this.shopLists[i].selectbox));
                    }
                    this.shopprice = (this.shopprice / 100).toFixed(2);
                    this.$store.commit("addShop", this.shopLists);
                    for (var i in allstr) {
                        if (allstr[i].indexOf("false") > -1) {
                            allfalsenum++;
                        }
                        if (allstr[i].indexOf("true") > -1) {
                            alltruenum++;
                        }
                    }
                    //所有取消和所有选中 引发全部按钮
                    if (allfalsenum == this.shopLists.length) {
                        this.checkall = false;
                        this.checkallfalse = "all";
                    } else {
                        // this.checkall = false;
                        this.checkallfalse = "noall";
                    }
                    if (alltruenum == this.shopLists.length) {
                        this.checkall = true;
                    } else {
                    }
                } else {
                    this.checkall = false;
                    this.shopprice = 0;
                    this.shopIntergral = 0;
                }
            }, 100);
        },
        getShopdata() {
            this.$vux.loading.show({ text: "Loading" });
            getShopping({})
                .then(response => {
                    if (response.rspCode == "0000") {
                        if (response.data.code == "0000") {
                            this.shopLists = response.data.productList;
                            this.shopLists.length == 0 && (this.showBg = true);
                            for (var i = 0; i < this.shopLists.length; i++) {
                                this.shopLists[i].selectbox =
                                    this.shopLists[i].selectbox === "false" ? false : true;
                                this.shopLists[i].buyNumber = Number(
                                    this.shopLists[i].buyNumber
                                );
                                this.shopLists[i].selectbox && (this.shopprice += this.shopLists[i].buyNumber * this.shopLists[i].salePrice)
                            }
                            !this.shopLists.some(item=>item.selectbox == false) && (this.checkall = true);
                            // 图片加域名
                            for (var item of this.shopLists) {
                                item.picUrl = this.imgUrl + item.picUrl;
                            }
                        } else if (response.data.code == "7000") {
                            this.showBg = true;
                            Toast({
                                message: "没有数据",
                                position: "bottom",
                                duration: 1000
                            });
                        }
                    } else {
                        Toast({
                            message: "请求失败",
                            position: "bottom",
                            duration: 1000
                        });
                    }
                    this.$vux.loading.hide();
                })
                .catch(error => {
                    console.log(error);
                    this.$vux.loading.hide();
                });
            // setTimeout(() => {
            //     this.$vux.loading.hide();
            // }, 2000);
        },
        change(item,type) {
            this.counts = (this.counts || 0) + 1
            if(this.counts <= this.shopLists.length){
                return;
            }
            if (item.buyNumber > 50) {
                MessageBox("", "最多购买50份哟");
            }
            Shopset({
                isAdd: "02",
                productNo: item.productNo,
                specIds: item.specId,
                buynum: item.buyNumber,
                selectBox: `${ !this.isWX ? !item.selectbox : item.selectbox}`
            }).then(response => {console.log(response)}).catch(error => { 
                console.log(error);
            });
            let is = this.shopLists.some(item=>(!this.isWX ? !item.selectbox : item.selectbox) == false);
            !is ? (this.checkall = true) : (this.checkall = false);
            // !this.shopLists.some(item=>item.selectbox == false) && (this.checkall = true);
        },
        //返回详情
        getcate(item) {
            this.$router.push({
                path: "/categoryDetail",
                query: {
                    cateNo: item.productNo
                }
            });
        },
        //全选
        slect() {
            for (var i = 0; i < this.shopLists.length; i++) {
                this.shopLists[i].selectbox = true;
                this.change(this.shopLists[i]);
            }
            this.sTimeout();
        },
        //取消全选
        canceLslect() {
            for (var i = 0; i < this.shopLists.length; i++) {
                this.shopLists[i].selectbox = false;
                this.change(this.shopLists[i]);
            }
            this.sTimeout();
        },
        //点击全选按钮
        selectdAll(){
            //微信和谷歌存在读取差异，以微信为准，测试时谷歌是运行不了的，所以做了个来判断
            if(this.isWX){
                !this.checkall ? this.canceLslect() : this.slect();
            }else{
                this.checkall ? this.canceLslect() : this.slect();
            }

        },
        //结算
        async settlement() {
            let tyarr = "";
            var noselctarr = [];
            for (var i = 0; i < this.shopLists.length; i++) {
                if (this.shopLists[i].selectbox) {
                    //是否实物，地址显示
                    tyarr += this.shopLists[i].productType;
                } else if (!this.shopLists[i].selectbox) {
                    noselctarr.push(this.shopLists[i]);
                }
            }
            this.$store.commit("setno", noselctarr);
            //是否实物，地址显示
            if (tyarr.indexOf("1") > -1) {
                this.shopType = "1";
            } else {
                this.shopType = "3";
            }
            let totaljson = {
                shopType: this.shopType
            };
            let shoparr = [];
            for (var i = 0; i < this.shopLists.length; i++) {
                if (this.shopLists[i].selectbox) {
                    shoparr.push(this.shopLists[i]);
                }
            }
            let goResultpage = true;
            if (shoparr.length == 0) {
                MessageBox("", "请选择商品");
                return false;
            }
            //计算运费，所选商品总额
            this.$vux.loading.show({
                text: "Loading"
            });
            await shoppingOrders({ productList: shoparr })
                .then(response => {
                    console.log(response)
                    if (response.rspCode == "0000") {
                        if (response.data.resultCode == "00") {
                            let orderList = Object.assign({}, response.data);
                            totaljson.shopIntergral = orderList.totalIntegral;
                            totaljson.shopprice = orderList.totalAmount;
                            totaljson.freight = orderList.totalFreight;
                            // totaljson.couponList = orderList.couponList;
                            totaljson.couponList = orderList.couponList.map(item=>{
                                item.haveclick = item.couponNo == response.data.checkedCouponNo
                                return item;
                            })
                            totaljson.a = "orderList.couponList";
                            goResultpage = true;
                        } else {
                            MessageBox("",response.data.resultMesg || "结算失败");
                            goResultpage = false;
                        }
                    } else if (response.rspCode == "1999") {
                        MessageBox("", response.rspMsg || "结算失败");
                        this.$router.push({ path: "/" });
                    } else {
                        MessageBox("", "结算失败");
                        goResultpage = false;
                    }
                    this.$vux.loading.hide();
                })
                .catch(
                    error => console.log(error),
                    (goResultpage = false),
                    this.$vux.loading.hide()
                );
            //是否有库存，计算是否成功，发送选择商品和计算数据
            if (goResultpage) {
                this.$store.commit("addtotal", totaljson);
                this.$store.commit("slectShop", shoparr);
                if (shoparr.length < 1) {
                    MessageBox("", "请选择商品");
                } else {
                    this.$store.commit("setno", noselctarr);
                    this.$store.commit("mchtCouponList", totaljson.couponList);
                    this.$router.push({
                        path: "/shopResult"
                    });
                }
            }
        },
        deleteshop(item) {
            if (item.specId) {
                var jsonObj = {
                    type: "02",
                    specIdList: [item.specId],
                    productNoS: [item.productNo]
                };
            } else {
                var jsonObj = { type: "02", productNoS: [item.productNo] };
            }
            //  02 删除 01 购买
            deletShop(jsonObj)
                .then(response => {
                    if (response.rspCode == "0000") {
                        if (response.data.code == "0000") {
                            Toast({
                                message: response.data.rspMsg || "操作成功",
                                position: "middle",
                                duration: 3000
                            });
                        } else {
                            MessageBox(
                                "",
                                response.data.resultMesg || "删除失败"
                            );
                        }
                    } else {
                        MessageBox("", "删除失败");
                    }
                })
                .catch(error => console.log(error));
        },

        //滑动开始
        touchStart(e) {
            // 记录初始位置
            this.startX = e.touches[0].clientX;
        },
        //滑动结束
        touchEnd(e) {
            // 当前滑动的父级元素
            let parentElement = e.currentTarget.parentElement;
            // 记录结束位置
            this.endX = e.changedTouches[0].clientX;

            // 左滑
            if (
                parentElement.dataset.type == 0 &&
                this.startX - this.endX > 30
            ) {
                this.restSlide();
                parentElement.dataset.type = 1;
            }
            // 右滑
            if (
                parentElement.dataset.type == 1 &&
                this.startX - this.endX < -30
            ) {
                this.restSlide();
                parentElement.dataset.type = 0;
            }
            this.startX = 0;
            this.endX = 0;
        },
        //判断当前是否有滑块处于滑动状态
        checkSlide() {
            let listItems = document.querySelectorAll(".listchild");
            for (let i = 0; i < listItems.length; i++) {
                if (listItems[i].dataset.type == 1) {
                    return true;
                }
            }
            return false;
        },
        //复位滑动状态
        restSlide() {
            let listItems = document.querySelectorAll(".listchild");
            // 复位
            for (let i = 0; i < listItems.length; i++) {
                listItems[i].dataset.type = 0;
            }
        },
        //删除
        deleteItem(ev, index, item) {
            this.deleteshop(item);
            ev.stopPropagation();
            // 复位
            this.restSlide();
            // 页面删除
            this.shopLists.splice(index, 1);
            //删除影响页面总金额的变化
            this.clicks();
            // 后台逻辑删除
        }
    },
    destroyed() {},
    watch: {
        // checkall() {
        //     if (this.checkall) {
        //         this.slect();
        //     } else {
        //         this.canceLslect();
        //     }
        // }
    }
};
</script>
<style lang="less" scoped>
@import "./../css/ckecked.css";
// .list{
//   position: relative;
//   background-color: red;
// }
.xnumber {
    margin: 0px;
    padding: 0px;
    .vux-number-selector-sub {
        padding: 0;
    }
    .vux-number-input {
        padding: 0;
    }
    .vux-number-selector-plus {
        padding: 0;
    }
}
.vux-number-selector {
    padding: 0px !important;
}
.xnumber:before {
    border: none;
}
.cont {
    position: fixed;
    top: 0px;
    width: 100%;
    height: 100%;
    background-color: #f1f2f3;
    z-index: 9;
}
.listbox {
    position: relative;
    z-index: 10;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    background-color: #f1f2f3;
    padding: 1rem 10px 60px 10px;
    overflow-x: auto;
    // overflow-y: hidden;
    overflow: hidden;
    color: black;
    .listchild[data-type="0"] {
        transform: translate3d(0, 0, 0);
        transition: all 0.3s ease;
        position: relative;
        .delte {
            position: absolute;
            top: 0px;
            right: -111px;
            width: 100px;
            height: 7rem;
            background-color: red;
            font-size: 20px;
            color: #f3ecec;
            line-height: 6rem;
        }
    }
    .listchild[data-type="1"] {
        transform: translate3d(-100px, 0, 0);
        transition: all 0.3s ease;
        position: relative;
        .delte {
            position: absolute;
            top: .7rem;
            right: -111px;
            width: 100px;
            height: 7rem;
            background-color: red;
            font-size: 20px;
            color: #f3ecec;
            line-height: 6rem;
        }
    }
    .imgshou {
        height: 8rem;
        display: flex;
        border-radius:8px;
        background-color: #fff;
        align-items: center;
        padding: 0px 3px 0px 3px;
        box-sizing: border-box;
        justify-content: space-between;
        margin-bottom: 0.5rem;
        .checkbox {
            width: 40px;
            height: 30px;
            border-radius: 50%;
        }
        img {
            height: 5.5rem;
            width: 7.4rem;
            border-radius: 7px;
            margin: 0 6px 0 6px;
        }
        .conts {
            width: 100%;
            height: 7rem;
            .s {
                width: 65%;
            }
            & .conts-con{
                margin-bottom:-4px;
            }
            p {
                text-align: left;
                height: 2.3rem;
                align-items: flex-end;
                display: flex;
                box-sizing: border-box;
                justify-content: space-between;
            }
            .guige {
                justify-content: flex-start;
                span {
                    margin-right: 5px;
                }
            }
        }
    }
    .nodata {
        // margin-top: 20%;
        font-size: 18px;
        position: relative;
        width: 100%;
        height: 100%;
        .fontcolor {
            color: #c8c8c8;
        }
        img {
            width: 50%;
        }
    }
}
@media (max-width: 321px) {
    .listbox .list .listcontent .content .cright p {
        width: 110%;
        font-size: 6px;
    }
}
@media (min-width: 321px) {
    .listbox .list .listcontent .content .cright p {
        padding-left: 5px;
    }
}
.shopfoot {
    position: fixed;
    left: 0;
    z-index: 999;
    bottom: 0;
    width: 100%;
    height: 50px;
    background-color: white;
    display: flex;
    align-items: center;
    padding: 0 0 0 3%;
    box-sizing: border-box;
    .confoot {
        width: 100%;
        height: 50px;
        padding: 0 0 0 3px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .left {
            width: 100%;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-right: 10px;
            box-sizing: border-box;
            .one {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            .two {
                text-align: left;
                word-break: break-all;
            }
        }
        .button {
            width: 100px;
            height: 50px;
            line-height: 50px;
            font-size: 18px;
            color: #ffffff;
            background-color: #ed6e36;
        }
        .check {
            padding-right: 5px;
        }
    }
}
.cartP{
    margin-left:.5rem;
    margin-right:.4rem;
}
</style>
 

